<?php

//正则匹配preg_match||preg_match_all
$pattern = '/[0-9]/';
$subject = 'dsfas223dasfdasf78dsfds46';
$m1 = $m2 = [];
$t1 = preg_match($pattern, $subject, $m1);
$t2 = preg_match_all($pattern, $subject, $m2);
echo '//preg_match匹配次数到的第一个<br>';
echo '源：'.$subject.'<br>';
echo '规则：'.$pattern.'<br>';
echo '返回匹配次数'.$t1;
show_resault($m1);
echo '//preg_match_all匹配所有返回<br>';
echo '源：'.$subject.'<br>';
echo '规则：'.$pattern.'<br>';
echo '返回匹配次数'.$t2;
show_resault($m2);

//正则替换preg_replace||preg_filter
$subject = ['dsfas', '123dasf', '78dsf', 'ds46'];
$pattern = ['/[0123]/', '/[456]/', '/[789]/', '/asf/'];
$replacment = ['士', '大', '夫', '飞度'];
//数组每个item都会显示出来返回
echo '//preg_replace数组每个item都会显示出来返回<br>';
echo '源：<br>';
print_r($subject);
echo '规则：<br>';
print_r($pattern);
echo '替换源：<br>';
print_r($replacment);
$str1 = preg_replace($pattern, $replacment, $subject);
show_resault($str1);
//只有被替换的iten才会返回
echo '//preg_filter只有被替换的iten才会返回<br>';
echo '源：<br>';
print_r($subject);
echo '规则：<br>';
print_r($pattern);
echo '替换源：<br>';
print_r($replacment);
$str2 = preg_filter($pattern, $replacment, $subject);
show_resault($str2);

//正则返回preg_grep
$pattern = '/[0-9]/';
$subject = ['dsfas', '123dasf', '78dsf', 'ds46'];
//只返回匹配到的字符
echo '//preg_grep只返回匹配到的字符<br>';
echo '源：<br>';
print_r($subject);
echo '<br>规则：'.$pattern.'<br>';
$arr = preg_grep($pattern, $subject);
show_resault($arr);

//正则把字符串转数组preg_split
$pattern = '/3/';
$subject = 'dsfas3dasfdasf3dsfds3asdf';
echo '//preg_split正则把字符串转数组<br>';
echo '源：'.$subject.'<br>';
echo '规则：'.$pattern.'<br>';
$arr = preg_split($pattern, $subject);
show_resault($arr);

//正则转义preg_quote
$str = 'qwer{asdf}[1234]';
echo '//preg_quote正则转义<br>';
echo '源：'.$str.'<br>';
$arr = preg_quote($str);
show_resault($arr);


//修正模式
$pattern = '/imooc.+123/';
$subject = 'I Love imooc__123123123123123123123123';
$m1 = $m2 = [];
//默认是贪婪模式
echo '//修正模式，默认为贪婪模式<br>';
echo '源：'.$subject.'<br>';
echo '规则：'.$pattern.'<br>';
preg_match($pattern, $subject, $m1);
show_resault($m1);
/*修正模式标识
 * U - 懒惰模式
 * i - 忽略英文大小写
 * x - 忽略空白
 * s - 让元字符'.'匹配包括换行符行符在乃的所有字符
 * e -
 * */
$pattern = '/i  MooC.+123/Uix';
echo
    '//修正模式<br>
U - 懒惰模式<br>
i - 忽略英文大小写<br>
x - 忽略空白<br>
s - 让元字符'.'匹配包括换行符行符在乃的所有字符<br>
e -<br>
默认为贪婪模式<br>
模式可以叠加<br>';
echo '源：'.$subject.'<br>';
echo '规则：'.$pattern.'<br>';
preg_match($pattern, $subject, $m2);
show_resault($m2);
//"^\w+(\.\w+)*@\w+(\.\w+)+$"邮件正则
exit;

function show_resault($var = null){
    if(empty($var)){
        echo 'null';
    }elseif (is_array($var) || is_object($var)){
        echo '<pre>';
        print_r($var);
        echo '</pre>';
    }else{
        echo $var;
    }
    echo '<hr />';
}